﻿using System;
using System.Web;

namespace U01_boke
{
    public class Global : HttpApplication
    {
        public static object objLock = new object();

        protected void Application_Start(object sender, EventArgs e)
        {

        }
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.AddHeader("Access-Control-Allow-Origin", "*");
            Response.ContentType = "application/json";
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            //获取请求的IP
            string ip = IPHelper.GetCurrentIP();

            //记录IP
            if (!string.IsNullOrEmpty(ip) && !CacheManage.Contain(ip))
            {
                lock (objLock)
                {
                    if (!CacheManage.Contain(ip))
                    {
                        CacheManage.Add(ip, Api.RecordIP(ip));
                    }
                }
            }
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception LastException = Server.GetLastError();
            LastException = LastException.InnerException ?? LastException;
            int status = 201;

            //危险字符异常
            if ((LastException as HttpRequestValidationException) != null)
            {
                LastException = new ResultException("请好好说话可以吗");
            }
            //HTTP异常
            if ((LastException as HttpException) != null)
            {
                status = (LastException as HttpException).GetHttpCode();
            }
            //自定义异常
            if ((LastException as ResultException) != null)
            {
                status = (LastException as ResultException).status;
            }
            OperationResult result = new OperationResult(LastException.Message, status);
            Response.Write(SerializerFactory.Serialize(result));
            Response.End();
        }
    }
}